package com.example.backend.controller;

import com.example.backend.dto.WebSocketMessageDto;
import com.example.backend.service.WebSocketService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * WebSocket控制器
 * 提供WebSocket相关的REST API
 */
@Slf4j
@RestController
@RequestMapping("/api/websocket")
@RequiredArgsConstructor
public class WebSocketController {

    private final WebSocketService webSocketService;

    /**
     * 发送消息给指定用户
     */
    @PostMapping("/send/user/{username}")
    public ResponseEntity<Map<String, Object>> sendToUser(
            @PathVariable String username,
            @RequestBody WebSocketMessageDto message) {
        
        try {
            webSocketService.sendToUser(username, message);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "消息发送成功");
            response.put("username", username);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送消息失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "消息发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 发送消息给多个用户
     */
    @PostMapping("/send/users")
    public ResponseEntity<Map<String, Object>> sendToUsers(
            @RequestBody Map<String, Object> request) {
        
        try {
            @SuppressWarnings("unchecked")
            List<String> usernames = (List<String>) request.get("usernames");
            WebSocketMessageDto message = (WebSocketMessageDto) request.get("message");
            
            webSocketService.sendToUsers(usernames, message);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "消息发送成功");
            response.put("userCount", usernames.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送消息失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "消息发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 广播消息
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcast(@RequestBody WebSocketMessageDto message) {
        try {
            webSocketService.broadcastMessage(message);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "广播消息发送成功");
            response.put("onlineUserCount", webSocketService.getOnlineUserCount());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("广播消息失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "广播消息失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 发送工单分配通知
     */
    @PostMapping("/notify/ticket-assigned")
    public ResponseEntity<Map<String, Object>> notifyTicketAssigned(
            @RequestParam String assigneeUsername,
            @RequestParam Long ticketId,
            @RequestParam String ticketTitle,
            @RequestParam String assignerName) {
        
        try {
            webSocketService.sendTicketAssignedNotification(assigneeUsername, ticketId, ticketTitle, assignerName);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "工单分配通知发送成功");
            response.put("assignee", assigneeUsername);
            response.put("ticketId", ticketId);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送工单分配通知失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "工单分配通知发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 发送工单状态变更通知
     */
    @PostMapping("/notify/ticket-status-changed")
    public ResponseEntity<Map<String, Object>> notifyTicketStatusChanged(
            @RequestParam String username,
            @RequestParam Long ticketId,
            @RequestParam String ticketTitle,
            @RequestParam String oldStatus,
            @RequestParam String newStatus) {
        
        try {
            webSocketService.sendTicketStatusChangedNotification(username, ticketId, ticketTitle, oldStatus, newStatus);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "工单状态变更通知发送成功");
            response.put("username", username);
            response.put("ticketId", ticketId);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送工单状态变更通知失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "工单状态变更通知发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 发送新评论通知
     */
    @PostMapping("/notify/comment-added")
    public ResponseEntity<Map<String, Object>> notifyCommentAdded(
            @RequestParam String username,
            @RequestParam Long ticketId,
            @RequestParam String ticketTitle,
            @RequestParam String commenterName,
            @RequestParam String commentContent) {
        
        try {
            webSocketService.sendNewCommentNotification(username, ticketId, ticketTitle, commenterName, commentContent);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "新评论通知发送成功");
            response.put("username", username);
            response.put("ticketId", ticketId);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送新评论通知失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "新评论通知发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 发送系统通知
     */
    @PostMapping("/notify/system")
    public ResponseEntity<Map<String, Object>> notifySystem(
            @RequestParam String title,
            @RequestParam String content,
            @RequestParam(defaultValue = "2") Integer priority) {
        
        try {
            webSocketService.sendSystemNotification(title, content, priority);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "系统通知发送成功");
            response.put("onlineUserCount", webSocketService.getOnlineUserCount());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送系统通知失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "系统通知发送失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 获取在线用户信息
     */
    @GetMapping("/online-users")
    public ResponseEntity<Map<String, Object>> getOnlineUsers() {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("onlineUserCount", webSocketService.getOnlineUserCount());
            response.put("onlineUsers", webSocketService.getOnlineUsers());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取在线用户信息失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取在线用户信息失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 检查用户是否在线
     */
    @GetMapping("/check-online/{username}")
    public ResponseEntity<Map<String, Object>> checkUserOnline(@PathVariable String username) {
        try {
            boolean isOnline = webSocketService.isUserOnline(username);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("username", username);
            response.put("isOnline", isOnline);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("检查用户在线状态失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "检查用户在线状态失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }
}
